package com.dengyafei.interceptor;

import com.dengyafei.annotation.JwtToken;
import com.dengyafei.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author 邓亚非
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object o) throws Exception {

//        请求头中取出token
        String token = null;
        try {
            token = JwtUtil.getRealToken(httpServletRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        如果没有映射方法直接通过
        if (!(o instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) o;
        Method method = handlerMethod.getMethod();
//        检查需要登录的注解
        if (method.isAnnotationPresent(JwtToken.class)) {
            JwtToken jwtToken = method.getAnnotation(JwtToken.class);
            if (jwtToken.required()) {
                if (token == null) {
                   log.info("token is null");
                    throw new RuntimeException("无token,请重新登录");
                }
                String userInfo = JwtUtil.getUserInfo(token);
//                验证token
                boolean verify = JwtUtil.verify(token);
                if (verify) {
                    log.info("验证通过");
                } else {
                    log.error("验证失败");
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)
            throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
